<template>
    <view class="page-box">
        <view class="header row bothSide">
            <view class="column">
                <text class="t1">智能匹配系统</text>
                <text class="t2">根据客户提供的资料系统生成产品方案</text>
            </view>
            <view class="bg">
                <image src="../../static/bg2.png" mode="aspectFill"></image>
            </view>
        </view>
        <view class="from-box">
            <view class="title">车主信息</view>
            <view class="input-box column">
                <view class="label required">年龄：</view>
                <input type="text" placeholder="请输入年龄" placeholder-style="color: #c3c3c3;" class="uni-input" v-model="form.age" />
            </view>
            <view class="input-box column">
                <view class="label required">常驻城市：</view>
                <view class="dropdown row bothSide verCenter" style="width: 100%;">
                    <view class="dropdown-wrap" style="width: 100%;">
                        <uni-data-picker :localdata="region" placeholder="请选择常驻城市" popup-title="请选择常驻城市" @nodeclick="onnodeclick($event,1)"></uni-data-picker>
                    </view>
                    <text class="iconfont icon-juxing" style="margin-right: 0;"></text>
                </view>
            </view>
            <view class="input-box column">
                <view class="label required">是否有未结案：</view>
                <view class="choice row bothSide verCenter">
                    <picker @change="bindPickerChange($event,1)" :value="is_unresolved_case_index" :range="is_unresolved_case" :range-key="'name'" style="width: 100%;">
                        <view class="picker-wrap row bothSide verCenter" style="width: 100%;">
                            <text class="uni-text" :style="is_unresolved_case_index === '' ? { color: '#c3c3c3' } : {}">{{ is_unresolved_case_index === '' ?  '请选择是否有未结案，' : is_unresolved_case[is_unresolved_case_index].name}}</text>
                        </view>
                    </picker>
                    <text class="iconfont icon-juxing"></text>
                </view>
            </view>
            <view class="input-box column">
                <view class="label required">是否有当前逾期：</view>
                <view class="choice row bothSide verCenter">
                    <picker @change="bindPickerChange($event,2)" :value="is_overdue_credit_index" :range="is_overdue_credit" :range-key="'name'" style="width: 100%;">
                        <view class="picker-wrap row bothSide verCenter" style="width: 100%;">
                            <text class="uni-text" :style="is_overdue_credit_index === '' ? { color: '#c3c3c3' } : {}">{{ is_overdue_credit_index === '' ?  '请选择是是否有当前逾期' : is_overdue_credit[is_overdue_credit_index].name}}</text>
                        </view>
                    </picker>
                    <text class="iconfont icon-juxing"></text>
                </view>
            </view>
            <view class="input-box column">
                <view class="label required">是否白户：</view>
                <view class="choice row bothSide verCenter">
                    <picker @change="bindPickerChange($event,3)" :value="is_no_credit_index" :range="is_no_credit" :range-key="'name'" style="width: 100%;">
                        <view class="picker-wrap row bothSide verCenter" style="width: 100%;">
                            <text class="uni-text" :style="is_no_credit_index === '' ? { color: '#c3c3c3' } : {}">{{ is_no_credit_index === '' ?  '请选择是否白户' : is_no_credit[is_no_credit_index].name}}</text>
                        </view>
                    </picker>
                    <text class="iconfont icon-juxing"></text>
                </view>
            </view>
            <view class="input-box column">
                <view class="label required">近1个月征信查询次数：</view>
                <input type="text" placeholder="请输入近1个月征信查询次数" placeholder-style="color: #c3c3c3;" class="uni-input" v-model="form.credit_query_counts_within_one_month" />
            </view>
            <view class="input-box column">
                <view class="label required">近2个月征信查询次数：</view>
                <input type="text" placeholder="请输入近2个月征信查询次数" placeholder-style="color: #c3c3c3;" class="uni-input" v-model="form.credit_query_counts_within_two_months" />
            </view>
        </view>
        <view class="from-box">
            <view class="title">车辆信息</view>
            <view class="input-box column">
                <view class="label required">车龄：</view>
                <input type="text" placeholder="请输入车龄" placeholder-style="color: #c3c3c3;" class="uni-input" v-model="form.car_age" />
            </view>
            <view class="input-box column">
                <view class="label required">车牌归属地：</view>
                <view class="dropdown row bothSide verCenter" style="width: 100%;">
                    <view class="dropdown-wrap" style="width: 100%;">
                        <uni-data-picker :localdata="region" placeholder="请选择车牌归属地" popup-title="请选择车牌归属地" @nodeclick="onnodeclick($event,2)"></uni-data-picker>
                    </view>
                    <text class="iconfont icon-juxing" style="margin-right: 0;"></text>
                </view>
            </view>
            <view class="input-box column">
                <view class="label required">车辆评估价：</view>
                <input type="text" placeholder="请输入车辆评估价" placeholder-style="color: #c3c3c3;" class="uni-input" v-model="form.car_valuation" />
            </view>
            <view class="input-box column">
                <view class="label required">是否事故车： </view>
                <view class="choice row bothSide verCenter">
                    <picker @change="bindPickerChange($event,6)" :value="is_accident_car_index" :range="is_accident_car" :range-key="'name'" style="width: 100%;">
                        <view class="picker-wrap row bothSide verCenter" style="width: 100%;">
                            <text class="uni-text" :style="is_accident_car_index === '' ? { color: '#c3c3c3' } : {}">{{ is_accident_car_index === '' ?  '请选择是否事故车' : is_accident_car[is_accident_car_index].name}}</text>
                        </view>
                    </picker>
                    <text class="iconfont icon-juxing"></text>
                </view>
            </view>
            <view class="input-box column">
                <view class="label required">是否公司车：</view>
                <view class="choice row bothSide verCenter">
                    <picker @change="bindPickerChange($event,7)" :value="is_company_car_index" :range="is_company_car" :range-key="'name'" style="width: 100%;">
                        <view class="picker-wrap row bothSide verCenter" style="width: 100%;">
                            <text class="uni-text" :style="is_company_car_index === '' ? { color: '#c3c3c3' } : {}">{{is_company_car_index === '' ? '请选择是否公司车' : is_company_car[is_company_car_index].name}}</text>
                        </view>
                    </picker>
                    <text class="iconfont icon-juxing"></text>
                </view>
            </view>
            <view class="input-box column">
                <view class="label required">是否新能源车：</view>
                <view class="choice row bothSide verCenter">
                    <picker @change="bindPickerChange($event,8)" :value="is_new_energy_vehicle_index" :range="is_new_energy_vehicle" :range-key="'name'" style="width: 100%;">
                        <view class="picker-wrap row bothSide verCenter" style="width: 100%;">
                            <text class="uni-text" :style="is_new_energy_vehicle_index === '' ? { color: '#c3c3c3' } : {}">{{is_new_energy_vehicle_index === '' ? '请选择是否新能源车' : is_new_energy_vehicle[is_new_energy_vehicle_index].name}}</text>
                        </view>
                    </picker>
                    <text class="iconfont icon-juxing"></text>
                </view>
            </view>
            <view class="input-box column">
                <view class="label required">是否直系过户：</view>
                <view class="choice row bothSide verCenter">
                    <picker @change="bindPickerChange($event,9)" :value="is_immediate_family_transfer_ownership_index" :range="is_immediate_family_transfer_ownership" :range-key="'name'" style="width: 100%;">
                        <view class="picker-wrap row bothSide verCenter" style="width: 100%;">
                            <text class="uni-text" :style="is_immediate_family_transfer_ownership_index === '' ? { color: '#c3c3c3' } : {}">{{is_immediate_family_transfer_ownership_index === '' ? '请选择是否直系过户' : is_immediate_family_transfer_ownership[is_immediate_family_transfer_ownership_index].name}}</text>
                        </view>
                    </picker>
                    <text class="iconfont icon-juxing"></text>
                </view>
            </view>
            <view class="input-box column">
                <view class="label required">是否免抵押：</view>
                <view class="choice row bothSide verCenter">
                    <picker @change="bindPickerChange($event,10)" :value="is_no_mortgage_index" :range="is_no_mortgage" :range-key="'name'" style="width: 100%;">
                        <view class="picker-wrap row bothSide verCenter" style="width: 100%;">
                            <text class="uni-text" :style="is_no_mortgage_index === '' ? { color: '#c3c3c3' } : {}">{{is_no_mortgage_index === '' ? '请选择是是否免抵押' : is_no_mortgage[is_no_mortgage_index].name}}</text>
                        </view>
                    </picker>
                    <text class="iconfont icon-juxing"></text>
                </view>
            </view>
        </view>
        <view class="btn row verCenter rowCenter" @click="submit()">提 交</view>
        <!-- 支付弹窗 -->
        <uni-popup ref="popup" background-color="#fff" borderRadius="20rpx 20rpx 20rpx 20rpx">
            <view class="popup-content column rowCenter verCenter">
                <view class="content column rowCenter verCenter">
                    <view class="ico">
                        <image src="../../static/pay.png" mode="aspectFill"></image>
                    </view>
                    <view class="row">
                        <text class="t2">请支付</text>
                        <text class="t3">{{amount}}元</text>
                        <text class="t2">开启智能匹配系统</text>
                    </view>
                    <view class="price row rowCenter verCenter">￥{{amount}}</view>
                    <view class="pay row rowCenter verCenter" @click="addMatchSearchPayOrder()">去支付</view>
                </view>
                <view class="iconfont icon-a-tubiaochangyongsousuo9" @click="close()"></view>
            </view>
        </uni-popup>
        <!-- 没有匹配产品 -->
        <uni-popup ref="popupMatchEmpty" background-color="#fff" borderRadius="20rpx 20rpx 20rpx 20rpx">
            <view class="popup-content column rowCenter verCenter">
                <view class="content column rowCenter verCenter">
                    <view class="ico">
                        <image src="http://www.szxlyc.com/uploads/product/20240928/Ao8aISSaZw0CNiIoYx50b9gShm60b49lsr4rG8Rs.png" mode="aspectFill"></image>
                    </view>
                    <view class="text row rowCenter" style="font-size: 30rpx;margin-top: 80rpx;font-weight: bold;">未匹配到产品</view>
                    <view class="text">
                        如您还有其他问题，请联系您的<text class="e1">邀请人</text>或添加<text class="e1">平台官方企微客服</text>进行解答
                    </view>
                    <image src="http://www.szxlyc.com/uploads/product/20250114/a18a122f439e884c4fd6d6af60388c2c.jpg" class="code" mode="aspectFill"></image>
                    <text class="code-text">平台官方企微客服</text>
                </view>
                <view class="iconfont icon-a-tubiaochangyongsousuo9" @click="close()"></view>
            </view>
        </uni-popup>
    </view>
</template>

<script>
    import { API } from '@/util/api.js';
    export default {
        data() {
            return {
                pay_id: '',
                amount: '',
                region: [], //城市列表
                is_unresolved_case: [{ name: '是', value: 1 }, { name: '否', value: -1 }],
                is_unresolved_case_index: '',
                is_overdue_credit: [{ name: '是', value: 1 }, { name: '否', value: -1 }],
                is_overdue_credit_index: '',
                is_no_credit: [{ name: '是', value: 1 }, { name: '否', value: -1 }],
                is_no_credit_index: '',
                credit_query_counts_within_one_month: [{ name: '0-5', value: 1 }, { name: '6-8', value: 2 }, { name: '9-10', value: 3 }, { name: '11-15', value: 4 }, { name: '不看征信', value: 5 }],
                credit_query_counts_within_one_month_index: '',
                credit_query_counts_within_two_months: [{ name: '0-8', value: 1 }, { name: '9-10', value: 2 }, { name: '11-15', value: 3 }, { name: '不看征信', value: 4 }],
                credit_query_counts_within_two_months_index: '',
                is_accident_car: [{ name: '是', value: 1 }, { name: '否', value: -1 }],
                is_accident_car_index: '',
                is_company_car: [{ name: '是', value: 1 }, { name: '否', value: -1 }],
                is_company_car_index: '',
                is_new_energy_vehicle: [{ name: '是', value: 1 }, { name: '否', value: -1 }],
                is_new_energy_vehicle_index: '',
                is_immediate_family_transfer_ownership: [{ name: '是', value: 1 }, { name: '否', value: -1 }],
                is_immediate_family_transfer_ownership_index: '',
                is_no_mortgage: [{ name: '是', value: 1 }, { name: '否', value: -1 }],
                is_no_mortgage_index: '',
                form: {
                    "age": "",
                    "car_valuation": "",
                    "resident_city": "",
                    "license_plate_city_id": "",
                    "is_unresolved_case": "",
                    "is_overdue_credit": "",
                    "is_no_credit": "",
                    "credit_query_counts_within_one_month": "",
                    "credit_query_counts_within_two_months": "",
                    "car_age": "",
                    "license_plate": "",
                    "is_accident_car": "",
                    "is_company_car": "",
                    "is_new_energy_vehicle": "",
                    "is_immediate_family_transfer_ownership": "",
                    "is_no_mortgage": ""
                }
            };
        },
        onLoad() {
            this.getRegion();
        },
        methods: {
            /**
             * 选择城市
             * @param {Object} node
             */
            onnodeclick(node, type) {
                if (type == 1) {
                    this.form.resident_city = node.value;
                } else {
                    this.form.license_plate_city_id = node.value;
                }
                console.log(node)
            },
            bindPickerChange(e, type) {
                const options = [
                    { indexKey: 'is_unresolved_case_index', formKey: 'is_unresolved_case', source: this.is_unresolved_case },
                    { indexKey: 'is_overdue_credit_index', formKey: 'is_overdue_credit', source: this.is_overdue_credit },
                    { indexKey: 'is_no_credit_index', formKey: 'is_no_credit', source: this.is_no_credit },
                    { indexKey: 'credit_query_counts_within_one_month_index', formKey: 'credit_query_counts_within_one_month', source: this.credit_query_counts_within_one_month },
                    { indexKey: 'credit_query_counts_within_two_months_index', formKey: 'credit_query_counts_within_two_months', source: this.credit_query_counts_within_two_months },
                    { indexKey: 'is_accident_car_index', formKey: 'is_accident_car', source: this.is_accident_car },
                    { indexKey: 'is_company_car_index', formKey: 'is_company_car', source: this.is_company_car },
                    { indexKey: 'is_new_energy_vehicle_index', formKey: 'is_new_energy_vehicle', source: this.is_new_energy_vehicle },
                    { indexKey: 'is_immediate_family_transfer_ownership_index', formKey: 'is_immediate_family_transfer_ownership', source: this.is_immediate_family_transfer_ownership },
                    { indexKey: 'is_no_mortgage_index', formKey: 'is_no_mortgage', source: this.is_no_mortgage }
                ];
                const selectedOption = options[type - 1];
                if (selectedOption) {
                    this[selectedOption.indexKey] = e.detail.value;
                    this.form[selectedOption.formKey] = selectedOption.source[e.detail.value].value;
                }
            },
            /**
             * 获取地址
             */
            getRegion() {
                this.request(API.getRegion, 'GET', {}, true).then(res => {
                    if (res.code === 0) {
                        this.region = res.data[0].children;
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
            },
            open() {
                this.$refs.popup.open('center');
            },
            close() {
                this.$refs.popup.close();
                this.$refs.popupMatchEmpty.close();
            },
            /**
             * 校验每个字段
             * @param {Object} field
             * @param {Object} message
             */
            validateField(field, message) {
                if (!field) {
                    uni.showToast({
                        title: message,
                        icon: 'none'
                    });
                    return false;
                }
                return true;
            },
            submit() {
                const validations = [
                    { field: this.form.age, message: '请输入年龄' },
                    { field: this.form.resident_city, message: '请选择常驻城市' },
                    { field: this.form.is_unresolved_case, message: '请选择是否有未结案' },
                    { field: this.form.is_overdue_credit, message: '请选择是否有当前逾期' },
                    { field: this.form.is_no_credit, message: '请选择是否白户' },
                    { field: this.form.credit_query_counts_within_one_month, message: '请选择近1个月征信查询次数' },
                    { field: this.form.credit_query_counts_within_two_months, message: '请选择近2个月征信查询次数' },
                    { field: this.form.car_age, message: '请输入车龄' },
                    { field: this.form.license_plate_city_id, message: '请选择车牌归属地' },
                    { field: this.form.car_valuation, message: '请输入车辆评估价' },
                    { field: this.form.is_accident_car, message: '请选择是否事故车' },
                    { field: this.form.is_company_car, message: '请选择是否公司车' },
                    { field: this.form.is_new_energy_vehicle, message: '请选择是否新能源车' },
                    { field: this.form.is_immediate_family_transfer_ownership, message: '请选择是否直系过户' },
                    { field: this.form.is_no_mortgage, message: '请选择是否免抵押' }
                ];

                // 循环遍历进行校验
                for (let validation of validations) {
                    if (!this.validateField(validation.field, validation.message)) {
                        return false;
                    }
                }

                this.request(API.submitMatchSearch, 'POST', this.form, true).then(res => {
                    if (res.code === 0) {
                        this.pay_id = res.data.id;
                        this.amount = res.data.amount;
                        this.$refs.popup.open(); //支付弹窗
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none',
                            duration: 5000
                        });
                    }
                });
            },
            /**
             * 添加智能匹配支付订单
             */
            addMatchSearchPayOrder() {
                this.request(API.addMatchSearchPayOrder, 'POST', { id: this.pay_id }, true).then(res => {
                    if (res.code === 0) {
                        this.initWeixinPay(res.data, res.data.pay_id);
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
            },
            /**
             * 初始化微信支付
             * @param {Object} payParams 支付参数
             * @param {String} pay_id 支付ID
             */
            initWeixinPay(payParams, pay_id) {
                const onBridgeReady = () => {
                    WeixinJSBridge.invoke('getBrandWCPayRequest', payParams, (res) => {
                        if (res.err_msg === "get_brand_wcpay_request:ok") {
                            this.close();
                            // 支付成功，开始轮询支付结果
                            this.startPollingPayResult(pay_id);
                        } else if (res.err_msg === "get_brand_wcpay_request:cancel") {
                            // 用户取消支付
                            uni.showToast({
                                title: '支付已取消',
                                icon: 'none'
                            });
                        } else {
                            // 其他情况，可能是支付失败或未知错误
                            uni.showToast({
                                title: '支付失败，请重试',
                                icon: 'none'
                            });
                        }
                    });
                };

                if (typeof WeixinJSBridge == "undefined") {
                    if (document.addEventListener) {
                        document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                    } else if (document.attachEvent) {
                        document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                        document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                    }
                } else {
                    onBridgeReady();
                }
            },
            /**
             * 开始轮询支付结果
             * @param {String} pay_id 支付ID
             */
            startPollingPayResult(pay_id) {
                let pollCount = 0;
                const maxPollCount = 100;
                const pollInterval = 1000;

                const pollPayResult = async () => {
                    while (pollCount < maxPollCount) {
                        await new Promise(resolve => setTimeout(resolve, pollInterval));

                        try {
                            const result = await this.getMatchSearchPayOrder(pay_id);
                            if (result.code === 0 && result.data.pay_status === 1) {
                                // 支付成功，显示提示并处理后续逻辑
                                uni.showToast({
                                    title: '支付成功',
                                    icon: 'success'
                                });
                                setTimeout(() => {
                                    this.close();
                                    this.getMatchSearch();
                                }, 2000);
                                return true;
                            }
                        } catch (error) {
                            console.error('查询支付结果出错:', error);
                        }
                        pollCount++;
                    }
                    return false;
                };

                pollPayResult().then(success => {
                    if (!success) {
                        console.log('支付结果查询超时');
                        uni.showToast({
                            title: '支付查询超时，请稍后检查订单状态',
                            icon: 'none'
                        });
                    }
                });
            },
            /**
             * 支付成功后定时任务查询支付结果
             * @param {Object} pay_id
             */
            getMatchSearchPayOrder(pay_id) {
                return this.request(API.getMatchSearchPayOrder, 'GET', { id: pay_id }, true);
            },
            /**
             * 支付后获取智能匹配结果
             */
            getMatchSearch() {
                this.request(API.getMatchSearch, 'GET', { id: this.pay_id }, false).then(res => {
                    if (res.code === 0) {
                        uni.hideToast();
                        uni.hideLoading();
                        let product_id = res.data.join(',');
                        if (product_id) {
                            //跳转匹配产品列表页面
                            uni.navigateTo({
                                url: `/pages/product/indexMatch?product_id=${product_id}`
                            });
                        } else {
                            this.$refs.popupMatchEmpty.open(); //未匹配到产品弹窗
                        }
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none',
                            duration: 5000
                        });
                    }
                });
            }
        }
    };
</script>

<style scoped lang="scss">
    @import '@/assets/css/productMatch/systemAutomaticMatching.scss';
</style>